/*
 * Copyright (C) 2010 Wim Crols <twimpiex@gnx.be>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package be.gnx.event.consumer.receiver.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

import be.gnx.event.consumer.receiver.EventProcessor;

public class AcceptedSocket implements Runnable {

	private final Socket socket;

	private final SocketListener socketListener;

	private final EventProcessor eventProcessor;

	protected AcceptedSocket(Socket socket, SocketListener socketListener,
			EventProcessor eventProcessor) {
		this.socket = socket;
		this.socketListener = socketListener;
		this.eventProcessor = eventProcessor;
	}

	public void run() {
		try {
			final ObjectInputStream objectInputStream = new ObjectInputStream(
					socket.getInputStream());

			while (true) {
				if (socketListener.isClosed()) {
					break;
				}
				eventProcessor.eventReceived(objectInputStream.readObject(),
						socket.getInetAddress().toString());
			}
		} catch (Exception ioException) {
			if (!socket.isClosed()) {
				System.err.println(ioException);
			}
		} finally {
			try {
				socket.close();
			} catch (IOException ioException) {
				if (!socketListener.isClosed()) {
					System.err.println(ioException);
				}
			}
		}
	}

}
